package is.glif.fenius.webui.topo;

import java.io.File;

import org.apache.cxf.helpers.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FileNetworkProvider implements NetworkProvider {
    private static FileNetworkProvider instance;
    public static FileNetworkProvider getInstance() {
        if (instance == null) {
            instance = new FileNetworkProvider();
        }
        return instance;
    }

    private String jsonString = null;
    private Long lastLoaded = null;
    private String fileName = "./config/networks.json";
    
    private FileNetworkProvider() {
        this.refresh();
    }

    public void refresh() {
        Long now = System.currentTimeMillis();
        boolean reload = false;
        if (lastLoaded == null) {
            lastLoaded = now;
            reload = true;
        }
        File edgeFile = new File(fileName);
        Long modified = edgeFile.lastModified();
        if (modified > lastLoaded) {
            reload = true;
        }
        if (reload) {
            System.out.println("reloading "+fileName);
            jsonString = FileUtils.getStringFromFile(edgeFile);
        }
    }

    public JSONArray getNetworks(String match) throws JSONException {
        refresh();
        match = match.replace("*", "");
        JSONArray result = new JSONArray();
        JSONArray tmp = new JSONArray(jsonString);
        for (int i = 0; i < tmp.length(); i++) {
            JSONObject obj = tmp.getJSONObject(i);
            String name = obj.getString("name");
            String id = obj.getString("id");
            if (match.equals("") || name.startsWith(match) || id.startsWith(match)) {
                result.put(obj);
            }
        }
        
        
        return result;
    }

}
